<template>
  <!-- 扣费信息提示弹窗 -->
  <uni-popup ref="popup" type="center" :mask-click="false">
    <view class="content-box">
      <view class="flc">
        <image class="top-img" src="@/static/img/global/call-tip-icon.png"></image>
        <view class="tips" style="margin-top: 33rem">温馨提示</view>
      </view>
      <uni-icons class="right-close" type="closeempty" size="14" @click="close()"></uni-icons>
      <view v-if="currentShowType == 1" class="content-center-label">
        <text>本次联系需要支付</text>
        <text class="content-label">{{ score }}</text>
        <text>积分，是否要继续？</text>
      </view>
      <view v-else-if="currentShowType == 2" class="content-center-label">
        <text>本次联系需要消耗</text>
        <text class="content-label">{{ score }}</text>
        <text>张次卡，是否要继续？</text>
      </view>
      <view class="content-desc">保护个人隐私，防范骚扰电话</view>
      <view class="flca mt25">
        <view class="cancel-btn" @click="close()">取消联系</view>
        <view class="confirm-btn" @click="confirmCall()">继续联系</view>
      </view>
      <view class="content-bottom flca" @click="changeLastTipsState">
        <image v-if="phoneTips == 0" class="bottom-check" src="@/static/img/global/check-false.png"></image>
        <image v-else class="bottom-check" src="@/static/img/global/check-true.png"></image>
        <text class="bottom-desc">当天不再进行提醒</text>
      </view>
    </view>
  </uni-popup>
</template>

<script>
const api = require('@/utils/request.js');
import commonMxins from '@/mixins/common.js';
export default {
  mixins: [commonMxins],
  data() {
    return {
      interval: null,
      callUrl: ['', '/purchaseInfo/queryContactDetail', '/saleInfo/queryContactDetail'],
      // 展示提示内容 1-积分提示 2-次卡提示 3-拨号前提示
      currentShowType: 0,
      score: 0,
      // 呼叫类型 1-采购 2-销售 3-其他
      callType: 1,
      callId: '',
      historyContactRecordId: '',
      phoneTips: 0, // 拨号提示
      popupType: 'tips',
      configUrlList: ['', '/purchaseInfo/beforeContact', '/saleInfo/beforeContact'],
      urlList: ['', '/purchaseInfo/contact', '/saleInfo/contact'],
      dataList: ['', { purchaseInfoId: '' }, { saleInfoId: '' }],
      isAlreadyComment: null, // 是否已拨号
      searchTimes: 0
    };
  },
  onShow() {},
  onLoad() {},
  methods: {
    async open(id, callType) {
      this.callId = id;
      this.callType = callType;
      this.dataList = ['', { purchaseInfoId: id }, { saleInfoId: id }];
      await this.queryTimesOrScore();
    },
    // 控制拨号提示展示
    controlPhoneTips() {
      this.phoneTips = uni.getStorageSync('phoneTips') || 0;
      if (this.currentShowType == 0) {
        return;
      }
      if (this.phoneTips >= new Date().getTime()) {
        this.confirmCall();
      } else {
        this.$refs.popup.open('center');
      }
    },
    close() {
      this.searchTimes = 0;
      clearInterval(this.interval);
      this.$refs.popup.close();
    },
    // 查询积分或者次卡扣分
    async queryTimesOrScore() {
      this.dataList = ['', { purchaseInfoId: this.callId }, { saleInfoId: this.callId }];
      const res = await api.request({ url: this.configUrlList[this.callType], data: this.dataList[this.callType], method: 'GET' });
      //  支付方式 "1"-积分   "2"-次卡
      if (res.code === 200) {
        const { cashPay, isAlreadyComment, payType, qty } = res.data;
        this.isAlreadyComment = isAlreadyComment;
        if (cashPay) {
          this.payCommit(4);
        } else {
          this.currentShowType = Number(payType);
          this.score = Number(qty);
          this.controlPhoneTips();
        }
      } else if (res.code == 500 && res.msg.includes('不足')) {
        this.currentShowType = 0;
        uni.showToast({
          title: res.msg,
          icon: 'none',
          duration: 3000,
          complete: () => {
            setTimeout(() => {
              uni.navigateTo({ url: '/pages/my/pay' });
            }, 3000);
          }
        });
        this.close();
      } else {
        this.currentShowType = 0;
        uni.showToast({
          title: res.msg,
          icon: 'none',
          duration: 3000
        });
        this.close();
      }
    },
    // 支付次卡操作
    async payCommit(wechatPayType) {
      let res = await api.request({
        url: '/wechatPay/initWechatPay',
        data: {
          wechatPayType,
          qty: '1',
          platform: '1'
        }
      });
      this.orderNo = res.data.orderNo;
      let t = this;
      wx.requestPayment({
        ...res.data,
        success(r) {
          t.queryOrderStatus();
        },
        fail() {
          uni.showToast({ title: '支付失败', icon: 'none' });
        }
      });
    },
    async queryOrderStatus() {
      clearTimeout(this.uid);
      let res = await api.request({ url: '/wechatPay/queryByOrderNo', data: { orderNo: this.orderNo }, method: 'GET' });
      if (res.data.thirdOrderStatus === '2') {
        uni.showToast({ title: '支付成功', icon: 'none' });
        this.confirmCall();
      } else if (res.data.thirdOrderStatus === '1' || res.data.thirdOrderStatus === '3') {
        this.uid = setTimeout(() => {
          this.queryOrderStatus();
        }, 1000);
      }
    },
    // 确认呼叫
    async confirmCall() {
      const res = await api.request({ url: this.urlList[this.callType], data: { ...this.dataList[this.callType], orderNo: this.orderNo, isAlreadyComment: this.isAlreadyComment ? this.isAlreadyComment : undefined, shareById: this.globalData.userInfo.shareId ? this.globalData.userInfo.shareId : undefined }, method: 'POST' });
      if (res.code === 200) {
        this.historyContactRecordId = res.data.historyContactRecordId;
        const systemInfo = uni.getSystemInfoSync();
        if (systemInfo.platform === 'android') {
          wx.makePhoneCall({
            phoneNumber: res.data.secretNo,
            success: result => {
              // 轮训查拨号状态，之后再打开评价弹窗
              this.searchTimes = 0;
              this.interval = setInterval(() => {
                this.getPhoneCallState(res.data.subId);
              }, 5000);
            },
            fail: error => {
              this.close();
              this.isAlreadyComment != 1 && this.$emit('openEvaluated', { releaseTime: '', startTime: '', targetId: this.callId, historyContactRecordId: this.historyContactRecordId });
            }
          });
        } else {
          uni.makePhoneCall({
            phoneNumber: res.data.secretNo,
            success: _result => {
              // 轮训查拨号状态，之后再打开评价弹窗
              this.searchTimes = 0;
              this.interval = setInterval(() => {
                this.getPhoneCallState(res.data.subId);
              }, 5000);
            },
            fail: error => {
              this.close();
              this.isAlreadyComment != 1 && this.$emit('openEvaluated', { releaseTime: '', startTime: '', targetId: this.callId, historyContactRecordId: this.historyContactRecordId });
            }
          });
        }
      } else {
        this.close();
        uni.showToast({
          icon: 'none',
          title: res.msg,
          duration: 2000
        });
      }
    },
    // 轮询查询数据
    // 埋点
    // 采购、销售评价弹窗，关闭必须提示，必须评论，不可关闭
    // 做全局控制，每次打开必弹窗
    async getPhoneCallState(subId) {
      const res = await api.request({ url: this.callUrl[this.callType], data: { subId }, method: 'GET' });
      if (res.code === 200 && res.data) {
        const { startTime, releaseTime } = res.data;
        if (startTime == releaseTime) {
          this.close();
          uni.showToast({
            title: '对方未接听电话，次卡或积分稍后退回!',
            icon: 'none',
            duration: 3000
          });
        } else {
          this.isAlreadyComment != 1 && this.$emit('openEvaluated', { releaseTime, startTime, targetId: this.callId, historyContactRecordId: this.historyContactRecordId });
          this.close();
        }
      } else {
        if (this.searchTimes > 60) {
          this.close();
        } else {
          this.searchTimes += 1;
        }
        this.$refs.popup.close();
      }
    },
    changeLastTipsState() {
      this.phoneTips = this.phoneTips ? 0 : new Date().getTime();
      uni.setStorageSync('phoneTips', this.phoneTips + 86400000);
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
